package com.koron.common.web.qrcode.service.impl;

import com.koron.common.core.util.qywx.QywxProperties;
import com.koron.common.core.util.weixin.WxProgramMessageUtil;
import com.koron.common.web.qrcode.bean.WxPageParameter;
import com.koron.common.web.qrcode.service.QRCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author twcao
 * @title: QRCodeServiceImpl
 * @projectName GDH_EAM_V2
 * @description: 二维码service
 * @date 2022/1/2513:12
 */
@Slf4j
@Service
public class QRCodeServiceImpl implements QRCodeService {

    @Autowired
    private WxProgramMessageUtil wxProgramUtil;

    @Autowired
    private QywxProperties qywxProperties;

    private RestTemplate template = new RestTemplate();

    @Override
    public ResponseEntity<byte[]> createMiniProgramQRCode(WxPageParameter parameter) {
        Map<String, Object> param = new HashMap<>();
        param.put("page", parameter.getPage());
        param.put("scene", parameter.getScene());
        param.put("check_path", parameter.isCheckPath());
        param.put("env_version", parameter.getEnvVersion());
        // 请求路径url
        String token = wxProgramUtil.getAccessTokenCache();
        log.info("token = {}", token);
        String url = qywxProperties.getCodeUnLimit() + "?access_token=" + token;
        log.info("url = {}", url);
        // 请求体body
        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity requestEntity = new HttpEntity(param, header);
        ResponseEntity<byte[]> entity = template.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
        HttpHeaders headers = entity.getHeaders();
        List<String> conentTypes = headers.get("Content-Type");
        StringBuilder sb = new StringBuilder();
        conentTypes.stream().forEach(contentType -> sb.append(contentType));
        Assert.isTrue(sb.toString().contains("image/jpeg"), "二维码生成失败");
        return entity;
    }
}
